package com.crdeng.system.service.impl;

import com.aliyun.oss.internal.OSSUtils;
import com.crdeng.handler.BusinessException;
import com.crdeng.response.ResultCode;
import com.crdeng.system.entity.Menu;
import com.crdeng.system.entity.Role;
import com.crdeng.system.mapper.RoleMapper;
import com.crdeng.system.service.MenuService;
import com.crdeng.system.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author crdeng
 * @since 2020-11-27
 */
@Service
public class
RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired(required = false)
    private RoleMapper roleMapper;

    @Autowired
    private MenuService menuService;
    /**
     * 查询角色已拥有的权限
     * @param id
     * @return
     */
    @Override
    public List<Integer> getMenuId(Integer id) {
        /*判断角色是否存在*/
        Role role = roleMapper.selectById(id);
        if (role==null){
            throw new BusinessException(ResultCode.ROLE_NOT_EXIST.getCode(),ResultCode.ROLE_NOT_EXIST.getMessage());
        }
        return roleMapper.getMenuId(id);
    }

    @Override
    public void saveMenu_Role(Integer id, List<Integer> menuIds) {
        /*判断角色是否存在*/
        Role role = roleMapper.selectById(id);
        if (role==null){
            throw new BusinessException(ResultCode.ROLE_NOT_EXIST.getCode(),ResultCode.ROLE_NOT_EXIST.getMessage());
        }
        //判断传入的菜单ID是否存在
        boolean flag = menuService.getMenuIdList().containsAll(menuIds);
        if (!flag){
            throw  new BusinessException(ResultCode.MENU_NOT_EXIST.getCode(),ResultCode.MENU_NOT_EXIST.getMessage());
        }

        roleMapper.deleteRole_Menu(id);

        //保存
        for (Integer menuId : menuIds) {
            roleMapper.saveRole_Menu(id,menuId);
        }



    }
}
